package com.zwan.oam_rtc.controller;

import com.alibaba.fastjson.JSON;
import com.zwan.oam_rtc.bean.appdemoentity.AcmeQueryParticipantsResponse;
import com.zwan.oam_rtc.bean.appdemoentity.AcmeQueryRoomListResponse;
import com.zwan.oam_rtc.bean.appdemoentity.AcmeRoomListResponse;
import com.zwan.oam_rtc.bean.appdemoentity.AcmeRtcParticipantsVo;
import com.zwan.oam_rtc.bean.appdemoentity.AcmeRtcRoomRecord;
import com.zwan.oam_rtc.bean.appdemoentity.LoginForm;
import com.zwan.oam_rtc.bean.appdemoentity.R;
import com.zwan.oam_rtc.bean.appdemoentity.SysUser;
import com.zwan.oam_rtc.bean.appdemoentity.TvResponse;
import com.zwan.oam_rtc.bean.appdemoentity.ZWUserListEntity;
import com.zwan.oam_rtc.bean.entity.CreateRoomData;
import com.zwan.oam_rtc.bean.entity.InviteSipData;
import com.zwan.oam_rtc.bean.req.*;
import com.zwan.oam_rtc.service.AppService;
import com.zwan.oam_rtc.service.RtcmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
@RequestMapping("/appapi")
public class AppController {
	@Autowired
	RtcmsService rtcmsService;

	@Autowired
	AppService appService;

	//登录，默认都通过
	@RequestMapping(value="/rs/login",method=RequestMethod.POST)
	public R login(@RequestBody LoginReq req) {

		long startTme = System.currentTimeMillis();
        // 生成token
        String token = String.valueOf(startTme);

		Map<String, Object> map = new HashMap<String, Object>();
        map.put("token", token);
        map.put("expire", 60);
        map.put("user", req.getUserName());
        log.info("%s login", req.getUserName());
        // 获取登录token
        return R.data(map);
	}

	@RequestMapping(value = "/rs/user", method = RequestMethod.GET)
    public R queryUserByCurrentId(HttpServletRequest request) {
		Cookie[] cookies = request.getCookies();
		SysUser user = new SysUser();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals("username")) {
					user.setUserName(cookie.getValue());				
				}
				if (cookie.getName().equals("password")) {
					user.setPassword(cookie.getValue());			
				}
				if (cookie.getName().equals("token")) {
					user.setUserId(appService.getCurrentUserId());			
				}
			}
		}	
		return R.data(user);
    }

	@GetMapping(value = "/rs/acmertc/room")
	public TvResponse room() {
		String result = rtcmsService.getConfListData();
		AcmeQueryRoomListResponse response = JSON.parseObject(result, AcmeQueryRoomListResponse.class);

		List<AcmeQueryRoomListResponse.DataEntity> dataEntities = response.getData();

		//包装好业务的返回结果
        List<AcmeRoomListResponse> roomListResponseList = new ArrayList<>();
        for (AcmeQueryRoomListResponse.DataEntity dataEntity : dataEntities) {
            //房间号
            try {
				List<ZWUserListEntity> userListEntities = dataEntity.getUserlist();
				List<AcmeRtcParticipantsVo> participants = appService.convertAcmeRtcParticipantsVoList(userListEntities);
				//封装ACME业务数据
                AcmeRoomListResponse roomListResponse = new AcmeRoomListResponse();
                roomListResponse.setParticipants(participants);
                roomListResponse.setCreateTime(dataEntity.getCreateTime());
                roomListResponse.setDescription(dataEntity.getRoom());
                roomListResponse.setRoomId(dataEntity.getId());
                roomListResponse.setCreateTrueName(dataEntity.getPromoter());
                roomListResponse.setPlatform(1);
                roomListResponse.setCreateUserName(dataEntity.getPromoter());
                roomListResponseList.add(roomListResponse);
			} catch (Exception e) {
				log.error(e.getMessage());
            }
		}
		return TvResponse.success(roomListResponseList);
	}

	@GetMapping(value = "/rs/acmertc/room/{roomName}")
    public TvResponse room(@PathVariable("roomName") String roomName) {
        AcmeRtcRoomRecord roomRecord = new AcmeRtcRoomRecord();
        return TvResponse.success(roomRecord);
    }

	@GetMapping(value = "/rs/acmertc/room/{roomName}/participants")
    public TvResponse participants(@PathVariable("roomName") String roomName) {
		QueryConfMemberInfoReq req = new QueryConfMemberInfoReq();
		req.setRoom(roomName);
		req.setSender("123456");
		String result = rtcmsService.getUserData(req);
		AcmeQueryParticipantsResponse response = JSON.parseObject(result, AcmeQueryParticipantsResponse.class);		
		if (response != null) {
            if (response.getError_code() == 200) {
                AcmeQueryParticipantsResponse.DataEntity dataEntity = response.getData();
                //收集所有的
                if (dataEntity.getUserlist() != null && dataEntity.getUserlist().size() > 0) {
                    return TvResponse.success(appService.convertAcmeRtcParticipantsVoList(dataEntity.getUserlist()));
                }
            }
            return TvResponse.error(response.getError());
        }
        return TvResponse.error("JSON.parseObject Error:" + result);
    }
}
